package com.io.service.impl;

import cn.hutool.core.util.IdUtil;
import com.io.dao.OrderDaoI;
import com.io.dto.ProductReq;
import com.io.entity.Order;
import com.io.service.OrderServiceI;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * The class/interface
 *
 * @author guodd
 * @version 1.0 use jdk 1.8
 */
@Service
public class OrderServiceImpl implements OrderServiceI {
    @Autowired
    private OrderDaoI orderDaoI;

    @Autowired
    private RocketMQTemplate rocketMQTemplate;

    // 半状态事务
    public void transactionSend(ProductReq productReqDTO) {
        String txId = IdUtil.fastSimpleUUID();
        // 发送半事务消息
        rocketMQTemplate.sendMessageInTransaction(
                "my-producer-group",
                "base-order",
                MessageBuilder.withPayload(productReqDTO).setHeader("txId", txId).build(),
                productReqDTO
        );
    }

    // 本地事务
    @Transactional
    public void transactionLocal(String txId, ProductReq productReqDTO) {
        Order order = new Order();
        BeanUtils.copyProperties(productReqDTO, order);
        orderDaoI.save(order);
        // 保存事务表
    }
}
